package com.ebupt.migu.music.common.util;

import com.ebupt.migu.music.common.util.excelSheet.ExcelBuilder;
import com.ebupt.migu.music.common.util.excelSheet.Sheet;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * excel导出方法
 * @Author zhuar
 */
@Slf4j
public class ExcelUtils {
    /** 生成excel的名字 */
    private String name;

    /** excel的版本 */
    private String version;

    /** 包含的sheet */
    private List<Sheet> sheets;

    public ExcelUtils() {
        this.version = "2007";
        this.sheets = new ArrayList<>();
    }

    public String getName() {
        return name;
    }

    public ExcelUtils setName(String name) {
        this.name = name;
        return this;
    }

    public String getVersion() {
        return version;
    }

    public ExcelUtils setVersion(String version) {
        this.version = version;
        return this;
    }

    public List<Sheet> getSheets() {
        return sheets;
    }

    /**
     * 设置sheets
     */
    public ExcelUtils setSheets(List<Sheet> sheets) {
        this.sheets = sheets;
        return this;
    }

    /** 添加单个sheet */
    public ExcelUtils addSheet(Sheet sheet) {
        this.sheets.add(sheet);
        return this;
    }

    /**
     * 保存excel
     * @param path
     * @return
     */
    public File saveAs(String path){
        boolean result=true;
        Workbook book = new SXSSFWorkbook();
        // 将数据填充到book
        ExcelBuilder.build(book,this);
        File excelFile = new File(path + File.separator + getName());
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(excelFile);
            book.write(fos);
        } catch (IOException e) {
            log.error("add message err", e);
            result=false;
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                log.error("add message err", e);
                result=false;
            }
            if (excelFile.exists()) {
                // excelFile.delete();
            }
        }
        return excelFile;
    }

    /**
     * 压缩并下载excel
     * @param response
     * @param request
     */
    public void zipAndResponse(HttpServletResponse response, HttpServletRequest request){
        new ExcelExportAction().exportExcel(response, request,this);
    }
}